package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.dto.IdentityVerifyDTO;
import com.powerbank.user.service.IdentityVerifyService;
import com.powerbank.user.vo.IdentityVerifyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

/**
 * 实名认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/identity")
public class IdentityController {

    @Autowired
    private IdentityVerifyService identityVerifyService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 提交身份证认证
     */
    @PostMapping("/verify")
    public Result<IdentityVerifyVO> submitIdentityVerify(@RequestBody @Valid IdentityVerifyDTO verifyDTO,
                                                         HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        IdentityVerifyVO result = identityVerifyService.submitIdentityVerify(userId, verifyDTO);
        return Result.success("实名认证申请提交成功，请等待审核", result);
    }

    /**
     * 获取用户认证信息
     */
    @GetMapping("/info")
    public Result<IdentityVerifyVO> getIdentityVerifyInfo(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        IdentityVerifyVO result = identityVerifyService.getIdentityVerifyInfo(userId);
        return Result.success(result);
    }

    /**
     * 重新提交认证
     */
    @PostMapping("/resubmit")
    public Result<IdentityVerifyVO> resubmitIdentityVerify(@RequestBody @Valid IdentityVerifyDTO verifyDTO,
                                                           HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        IdentityVerifyVO result = identityVerifyService.resubmitIdentityVerify(userId, verifyDTO);
        return Result.success("重新提交认证成功，请等待审核", result);
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }
}